package dialer.client.web.controlador;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DualListModel;

import dialer.ws.base.entity.Form;
import dialer.ws.base.entity.Item;
import dialer.ws.base.entity.vtelcom.Master;
import dialer.ws.base.exception.EntityNoFoundException;
import dialer.ws.business.service.MasterService;
import dialer.ws.common.util.CustomBase;
import dialer.ws.common.util.FacesUtils;

@ManagedBean(name = "master")
@SessionScoped
public class MasterController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7698170705928958302L;

	private static final Log log = LogFactory.getLog(MasterController.class);

	private String estado;
	private String nombre;
	private Date fchinicio;
	private Date fchfinal;
	private Integer intentos;
	private Integer scriptId;
	private String script;

	private String nombreCampo;
	private Integer tipo;

	private List<Master> listMaster;
	private List<String> listBase;
	private List<CustomBase> listCabecera;
	private List<CustomBase> listCampo;
	private List<Item> items;

	private DualListModel<Form> listFormulario;

	private Master selectedMaster;
	private Item item;

	@ManagedProperty("#{masterService}")
	private MasterService masterService;

	public MasterController() {
		clear();
	}

	@PostConstruct
	public void init() {
		listMaster = masterService.findAll();
	}

	public void actualizarLista() {
		log.info("### actualizarLista" + estado);
		if (estado != null && estado.equals("")) {
			listMaster = masterService.findAll();
		} else {
			// listMaster = masterService.getMasterByState(estado);
		}
	}

	public void reinit() {
		log.info("### reinit");
		item = new Item();
	}

	public void addCampo() {
		log.info("### guardarCampos");
		CustomBase cf = new CustomBase();
		cf.setName(nombreCampo);
		cf.setType(tipo);
		listCampo.add(cf);
		clearPanelCampos();
	}

	public void clearPanelCampos() {
		nombreCampo = "";
		tipo = 3;
		item = new Item();
		items.clear();
	}

	@SuppressWarnings("unchecked")
	public void change(ValueChangeEvent event) {
		log.info("### change");
		DualListModel<Form> nuevo = (DualListModel<Form>) event.getNewValue();
		listFormulario.setSource(nuevo.getSource());
		listFormulario.setTarget(nuevo.getTarget());
	}

	public void activar() {
		log.info("### activar");

	}

	public void desactivar() {
		log.info("### desactivar");

	}

	public void guardar() {
		log.info("### guardar");

	}

	public void load() throws EntityNoFoundException {
		log.info("### load");

	}

	public void editar() {
		log.info("### editar");

	}

	public void eliminar() {
		log.info("### eliminar");
	}

	public void handleFileUpload(FileUploadEvent event) {
		log.info("### handleFileUpload");
		try {
			InputStream is = event.getFile().getInputstream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			List<String> init = new ArrayList<String>();
			int numColumnas = 0;
			while (br.ready()) {
				String line = br.readLine().trim();
				String[] art = line.split(",");
				numColumnas = art.length;
				for (int i = 1; i < art.length; i++) {
					init.add(art[0] + "," + art[i]);
				}
			}

			String cabecera[] = new String[numColumnas - 1];
			int j = 0;
			for (String s : init) {
				if (s.split(",")[0].equals("")) {
					cabecera[j] = s.split(",")[1];
					j++;
				} else {
					break;
				}
			}

			Iterator<String> itr = init.iterator();
			int k = 0;
			while (itr.hasNext()) {
				@SuppressWarnings("unused")
				String element = itr.next();
				if (k < numColumnas - 1) {
					itr.remove();
				} else {
					break;
				}
				k++;
			}

			CustomBase cb = null;
			for (int l = 0; l < numColumnas - 1; l++) {
				cb = new CustomBase();
				cb.setName(cabecera[l]);
				listCabecera.add(cb);
			}

			int x = 0;
			for (String s : init) {
				if (x == numColumnas - 1) {
					x = 0;
				}
				for (int y = 0; y < numColumnas - 1; y++) {
					if (y == x) {
						listBase.add(s + "," + cabecera[x]);
						x++;
						break;
					}
				}
			}

			// HashSet<String> lista = new HashSet<String>();
			// for (String lb : listBase) {
			// log.info("### lista base " + lb);
			// lista.add(lb.split(",")[0]);
			// }

			// CustomBase cb = null;
			// Iterator<String> t = lista.iterator();
			// while (t.hasNext()) {
			// String element = t.next();
			// cb = new CustomBase();
			// cb.setName(element);
			// listCabecera.add(cb);
			// }

			FacesUtils.addInfoMessage("Satisfactorio", "base subido correctamente");
		} catch (IOException e) {
			log.error("### ERROR: " + e);
			FacesUtils.addErrorMessage("Error", "no se guardo correctamente");
		}
	}

	public void clear() {
		log.info("### clear");
		selectedMaster = new Master();
		listFormulario = new DualListModel<Form>(new ArrayList<Form>(), new ArrayList<Form>());

		listMaster = new ArrayList<Master>();
		listBase = new ArrayList<String>();
		listCabecera = new ArrayList<CustomBase>();
		items = new ArrayList<Item>();
		listCampo = new ArrayList<CustomBase>();
		item = new Item();
	}

	public String getEstado() {
		return estado;
	}

	public void setEstado(String estado) {
		this.estado = estado;
	}

	public String getNombre() {
		return nombre;
	}

	public void setNombre(String nombre) {
		this.nombre = nombre;
	}

	public Date getFchinicio() {
		return fchinicio;
	}

	public void setFchinicio(Date fchinicio) {
		this.fchinicio = fchinicio;
	}

	public Date getFchfinal() {
		return fchfinal;
	}

	public void setFchfinal(Date fchfinal) {
		this.fchfinal = fchfinal;
	}

	public Integer getIntentos() {
		return intentos;
	}

	public void setIntentos(Integer intentos) {
		this.intentos = intentos;
	}

	public String getScript() {
		return script;
	}

	public void setScript(String script) {
		this.script = script;
	}

	public List<Master> getListMaster() {
		return listMaster;
	}

	public void setListMaster(List<Master> listMaster) {
		this.listMaster = listMaster;
	}

	public Master getSelectedMaster() {
		return selectedMaster;
	}

	public void setSelectedMaster(Master selectedMaster) {
		this.selectedMaster = selectedMaster;
	}

	public MasterService getMasterService() {
		return masterService;
	}

	public void setMasterService(MasterService masterService) {
		this.masterService = masterService;
	}

	public List<String> getListBase() {
		return listBase;
	}

	public void setListBase(List<String> listBase) {
		this.listBase = listBase;
	}

	public List<CustomBase> getListCabecera() {
		return listCabecera;
	}

	public void setListCabecera(List<CustomBase> listCabecera) {
		this.listCabecera = listCabecera;
	}

	public String getNombreCampo() {
		return nombreCampo;
	}

	public void setNombreCampo(String nombreCampo) {
		this.nombreCampo = nombreCampo;
	}

	public Integer getTipo() {
		return tipo;
	}

	public void setTipo(Integer tipo) {
		this.tipo = tipo;
	}

	public List<CustomBase> getListCampo() {
		return listCampo;
	}

	public void setListCampo(List<CustomBase> listCampo) {
		this.listCampo = listCampo;
	}

	public List<Item> getItems() {
		return items;
	}

	public void setItems(List<Item> items) {
		this.items = items;
	}

	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public DualListModel<Form> getListFormulario() {
		return listFormulario;
	}

	public void setListFormulario(DualListModel<Form> listFormulario) {
		this.listFormulario = listFormulario;
	}

	public Integer getScriptId() {
		return scriptId;
	}

	public void setScriptId(Integer scriptId) {
		this.scriptId = scriptId;
	}

}
